package com.example.xinhuazidian

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.xinhuazidian.adapter.DiziguiAdapter
import com.example.xinhuazidian.utils.JsonFileUtil
import com.example.xinhuazidian.bean.Dizigui
import com.example.xinhuazidian.databinding.ActivityDiziguiBinding
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar

/**
 * 弟子规
 */
class DiziguiActivity : AppCompatActivity() {

    private lateinit var binding: ActivityDiziguiBinding
    private var fileName: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDiziguiBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initView()
    }

    private fun initView() {
        //沉浸状态栏
        ImmersionBar.with(this)
            .statusBarDarkFont(true)//状态栏字体是深色，不写默认为亮色
            .init()

        fileName = intent.getStringExtra("fileName")
        if (fileName != null) {
            load(fileName!!)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun load(fileName: String) {
        val str = JsonFileUtil.loadFile(this, fileName)

        val bean: Dizigui = Gson().fromJson(str, Dizigui::class.java)
        initAdapter(bean.content, fileName)

        binding.tvTitle.text = bean.title
        if ("" == bean.author) {
            binding.tvAuthor.visibility = View.GONE
        } else {
            binding.tvAuthor.visibility = View.VISIBLE
            binding.tvAuthor.text = bean.author
        }
    }

    private fun initAdapter(list: MutableList<Dizigui.ContentBean>, fileName: String) {
        val staggeredGridLayoutManager = StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL)
        binding.rv.layoutManager = staggeredGridLayoutManager

        //加载适配器
        val diziguiAdapter = DiziguiAdapter(list, fileName)
        binding.rv.adapter = diziguiAdapter
    }
}